package com.sky.controller.user;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.sky.dto.OrdersPageQueryDTO;
import com.sky.dto.OrdersPaymentDTO;
import com.sky.dto.OrdersSubmitDTO;
import com.sky.entity.Orders;
import com.sky.mapper.OrderMapper;
import com.sky.result.PageResult;
import com.sky.result.Result;
import com.sky.service.OrderService;
import com.sky.vo.OrderPaymentVO;
import com.sky.vo.OrderSubmitVO;
import com.sky.vo.OrderVO;
import com.sky.websocket.WebSocketServer;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Slf4j
@Api(tags = "C端订单相关接口")
@RestController("userOrderController")
@RequestMapping("/user/order")
public class OrderController {

    @Autowired
    private OrderService orderService;

    // 这里有点破坏代码结构了，但是没办法，为了跳过微信支付妥协太多了
    @Autowired
    private OrderMapper orderMapper;

    @Autowired
    private WebSocketServer webSocketServer;

    @ApiOperation("C端用户下单")
    @PostMapping("/submit")
    public Result<OrderSubmitVO> makeOrder (@RequestBody OrdersSubmitDTO ordersSubmitDTO) {
        log.info("用户下单:{}",ordersSubmitDTO);
        OrderSubmitVO orderSubmitVO = orderService.makeOrder(ordersSubmitDTO);
        return Result.success(orderSubmitVO);
    }

    /**
     * 订单支付
     *
     * @param ordersPaymentDTO
     * @return
     */
    @PutMapping("/payment")
    @ApiOperation("订单支付")
    public Result<OrderPaymentVO> payment(@RequestBody OrdersPaymentDTO ordersPaymentDTO) throws Exception {
        log.info("订单支付：{}", ordersPaymentDTO);
//        OrderPaymentVO orderPaymentVO = orderService.payment(ordersPaymentDTO);
//        log.info("生成预支付交易单：{}", orderPaymentVO);
        JSONObject jsonObject = JSON.parseObject("{\n" +
                "        \"nonceStr\": \"wx201410272009395522657a690389285100\",\n" +
                "        \"paySign\": \"string\",\n" +
                "        \"timeStamp\": \"string\",\n" +
                "        \"signType\": \"string\",\n" +
                "        \"packageStr\": \"string\"\n" +
                "    }");
        log.info("假数据JSONObject:{}",jsonObject);
        OrderPaymentVO orderPaymentVO = new OrderPaymentVO();
        orderPaymentVO.setNonceStr(jsonObject.getString("nonceStr"));
        orderPaymentVO.setPaySign(jsonObject.getString("paySign"));
        orderPaymentVO.setTimeStamp(jsonObject.getString("timeStamp"));
        orderPaymentVO.setSignType(jsonObject.getString("signType"));
        orderPaymentVO.setPackageStr(jsonObject.getString("packageStr"));
        log.info("返回假数据:{}",orderPaymentVO);
        // 支付成功更新数据
        orderService.paySuccess(ordersPaymentDTO.getOrderNumber());
        /**
         * 通过webSocket向客户端推送数据，这部分的代码本应写到支付成功的回调接口之后的，
         * 但是为了绕过微信支付，回调函数其实是不生效的，目前只能先写在这里了，以后的用的
         * 时候记得改一改，放到支付成功的回调接口那里去。
         */
        Orders order = orderMapper.getByNumber(ordersPaymentDTO.getOrderNumber());
        Map map = new HashMap();
        map.put("type",1); // 1表示来单提醒，2表示客户催单
        map.put("orderId",order.getId());
        map.put("content", "订单号" + order.getNumber());
        String socketMessage = JSON.toJSONString(map);
        webSocketServer.sendToAllClient(socketMessage);
        log.info("接单提醒:{}",socketMessage);
        return Result.success(orderPaymentVO);
    }

    /**
     * 查看订单详情
     * @param id
     * @return
     */
    @ApiOperation("查询订单详情")
    @GetMapping("/orderDetail/{id}")
    public Result<OrderVO> getOrderDetail (@PathVariable Long id) {
        log.info("查询订单详情:{}",id);
        OrderVO orderVO = orderService.getOrderDetail(id);
        return Result.success(orderVO);
    }

    /**
     * 历史订单查询
     * @param pageQueryDTO
     * @return
     */
    @ApiOperation("历史订单查询")
    @GetMapping("/historyOrders")
    public Result<PageResult> getHistoryOrders(OrdersPageQueryDTO pageQueryDTO){
        log.info("C端查询历史订单:{}",pageQueryDTO);
        PageResult pageResult
                = orderService.getHistoryOrders(pageQueryDTO);
        return Result.success(pageResult);
    }

    /**
     * C端取消订单
     * @param id
     * @return
     */
    @ApiOperation("C端取消订单")
    @PutMapping("cancel/{id}")
    public Result cancleOrder (@PathVariable Long id) {
        log.info("用户取消订单:{}",id);
        orderService.cancleOrder(id);
        return Result.success();
    }

    /**
     * C端再来一单
     * @param id
     * @return
     */
    @ApiOperation("C端再来一单")
    @PostMapping("/repetition/{id}")
    public Result repetition(@PathVariable Long id) {
        log.info("C端再来一单:{}",id);
        orderService.repetition(id);
        return Result.success();
    }

    /**
     * 用户催单
     * @param id
     * @return
     */
    @ApiOperation("用户催单")
    @GetMapping("/reminder/{id}")
    public Result urgeOrder (@PathVariable Long id) {
        log.info("用户催单:{}",id);
        orderService.urgeOrder(id);
        return Result.success();
     }

}
